package com.srmt.document.feishu;

import com.lark.oapi.Client;
import com.lark.oapi.core.enums.AppType;
import com.lark.oapi.core.enums.BaseUrlEnum;
import com.srmt.document.api.ContentReader;
import com.srmt.document.api.ContentWriter;
import com.srmt.document.api.DocumentManager;
import com.srmt.document.api.DocumentService;
import com.srmt.common.config.ApplicationConfig;
import com.srmt.document.feishu.internal.FeishuContentReader;
import com.srmt.document.feishu.internal.FeishuContentWriter;
import com.srmt.document.feishu.internal.FeishuDocumentManager;
import com.srmt.common.ratelimit.RateLimiter;
import com.srmt.common.ratelimit.RateLimiterFactory;
import com.srmt.feishu.client.FeishuClient;
import com.srmt.feishu.client.impl.DefaultFeishuClient;
import com.srmt.feishu.client.impl.RateLimitedFeishuClient;
import com.srmt.feishu.client.impl.RetryableFeishuClient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 飞书文档服务实现
 * 
 * @author YourCompany
 * @since 1.0.0
 */
public class FeishuDocumentService implements DocumentService {
    
    private static final Logger logger = LoggerFactory.getLogger(FeishuDocumentService.class);
    
    private final ApplicationConfig applicationConfig;
    private final FeishuClient client; // 使用接口类型
    private final DocumentManager documentManager;
    private final ContentWriter contentWriter;
    private final ContentReader contentReader;

    
    /**
     * 使用ApplicationConfig构造（推荐）
     * 
     * @param applicationConfig 应用配置对象
     */
    public FeishuDocumentService(ApplicationConfig applicationConfig) {
        if (applicationConfig == null) {
            throw new IllegalArgumentException("应用配置对象不能为null");
        }
        
        // 验证配置
        applicationConfig.validate();
        this.applicationConfig = applicationConfig;
        
        // 初始化飞书客户端
        this.client = initializeClient();
        
        // 初始化服务组件（使用新的ApplicationConfig）
        this.documentManager = new FeishuDocumentManager(client, applicationConfig);
        this.contentWriter = new FeishuContentWriter(client, applicationConfig);
        this.contentReader = new FeishuContentReader(client);
        
        logger.info("飞书文档服务已成功初始化");
    }
    
    /**
     * 初始化飞书客户端
     * 
     * @return FeishuClient 实例
     */
    private FeishuClient initializeClient() {
        logger.debug("使用应用ID初始化飞书客户端: {}", applicationConfig.getFeishu().getAppId());
        
        Client.Builder builder = Client.newBuilder(applicationConfig.getFeishu().getAppId(), applicationConfig.getFeishu().getAppSecret());
        
        // 设置应用类型，默认为SELF_BUILT
        builder.appType(AppType.SELF_BUILT);
        
        // 设置基础URL
        String baseUrl = applicationConfig.getFeishu().getBaseUrl();
        if (baseUrl != null && !baseUrl.isEmpty()) {
            if (baseUrl.contains("feishu")) {
                builder.openBaseUrl(BaseUrlEnum.FeiShu);
            } else if (baseUrl.contains("lark")) {
                builder.openBaseUrl(BaseUrlEnum.LarkSuite);
            }
        }
        
        // 设置超时
        int timeout = applicationConfig.getService().getTimeout();
        if (timeout > 0) {
            builder.requestTimeout(timeout, TimeUnit.MILLISECONDS);
        }
        
        // 设置日志级别
        boolean logReqAtDebug = applicationConfig.getService().isLogReqAtDebug();
        builder.logReqAtDebug(logReqAtDebug);
        
        // 创建原始客户端
        Client originalClient = builder.build();
        
        // 构建客户端链：原始客户端 -> 限流 -> 重试
        FeishuClient client;
        
        // 第一步：根据配置决定是否添加限流
        boolean rateLimitEnabled = applicationConfig.getRateLimit().isEnabled();
            
        if (rateLimitEnabled) {
            logger.info("速率限制已启用,正在创建限流飞书客户端");
            
            // 使用新配置创建限流器
            RateLimiter rateLimiter = RateLimiterFactory.createFromApplicationConfig(applicationConfig);
            client = new RateLimitedFeishuClient(originalClient, rateLimiter, applicationConfig.getRateLimit());
        } else {
            logger.info("速率限制已禁用,正在创建默认飞书客户端");
            // 创建默认客户端（不限流）
            client = new DefaultFeishuClient(originalClient);
        }
        
        // 第二步：根据配置决定是否添加重试
        boolean retryEnabled = applicationConfig.getRetry().isEnabled();
            
        if (retryEnabled) {
            logger.info("重试已启用,正在封装可重试飞书客户端");
            // 在现有客户端基础上添加重试功能
            client = new RetryableFeishuClient(client, applicationConfig.getRetry());
        } else {
            logger.info("重试已禁用");
            // fixme - 暂时总是启用重试
            client = new RetryableFeishuClient(client, applicationConfig.getRetry());
        }
        
        return client;
    }
    
    @Override
    public DocumentManager getDocumentManager() {
        return documentManager;
    }
    
    @Override
    public ContentWriter getContentWriter() {
        return contentWriter;
    }
    
    @Override
    public ContentReader getContentReader() {
        return contentReader;
    }
    
    
    /**
     * 获取配置
     * 
     * @return 配置对象
     */
    
    /**
     * 获取飞书客户端
     * 
     * @return 飞书客户端接口
     */
    public FeishuClient getClient() {
        return client;
    }
}